<template>
  <div class="box-container">
    <!-- 搜索 -->
     <div class="top-main">
    <el-form class="top-form-fl" :model="queryParams" ref="queryRef" label-width="auto" :inline="true">
      <el-form-item label="登录账号:"  prop="username">
        <el-input v-model="queryParams.username" placeholder="请输入登录账号" clearable/>
      </el-form-item>
      <el-form-item label="员工姓名:"  prop="nickname">
        <el-input v-model="queryParams.nickname" placeholder="请输入员工姓名" clearable/>
      </el-form-item>
      <el-form-item label="注册日期:"  prop="createStartTime" style="width: 400px;">
        <el-col :span="11">
          <el-date-picker v-model="queryParams.createStartTime" type="date" placeholder="开始日期" style="width: 100%" />
        </el-col>
        <el-col :span="2" class="text-center">
          <span class="text-gray-500">-</span>
        </el-col>
        <el-col :span="11">
          <el-date-picker v-model="queryParams.createEndTime" type="date" placeholder="结束日期" style="width: 100%" />
        </el-col>
      </el-form-item>
      <el-form-item label="手机号:"  prop="mobile">
        <el-input v-model="queryParams.mobile" placeholder="请输入手机号" clearable/>
      </el-form-item>
      <el-form-item label="邮箱地址:"  prop="email">
        <el-input v-model="queryParams.email" placeholder="请输入邮箱地址" clearable/>
      </el-form-item>
    </el-form>
     <div class="top-from-fr">
          <el-button class="top-Search" @click="getFilterData" type="primary">搜索</el-button>
          <el-button class="top-Refresh" @click="resetFrome">重置</el-button>
      </div>   
      </div>
    <el-button type="primary" :icon="Plus" style="float:right;margin: 20px;"
      @click="addPermissionRoleDialog">新增</el-button>

    <Table v-bind="tableData" @editPermissions="editPermissions" @deleteBox="deleteBox" @handleSwitch="handleSwitch"
      @pageChange="pageChange">
    </Table>

    <!-- 新增编辑弹窗 -->
    <el-dialog v-model="dialogUserRole" :title="typeOpen==1 ? '新增账户':'编辑账户'" @close="cancel" width="400px">
      <el-form :model="form" :rules="rules" ref="userRef" label-width="80px">
                  <el-form-item label="登录账户" prop="username">
                     <el-input :disabled="typeOpen!=1" v-model="form.username" placeholder="请输入账户" maxlength="20" />
                  </el-form-item>
                  <el-form-item label="登录密码" prop="password">
                     <el-input :disabled="typeOpen!=1" v-model="form.password" placeholder="请输入密码" maxlength="32" />
                  </el-form-item>
                  <el-form-item v-if="typeOpen==1" label="确认密码" prop="confirmPassword">
                     <el-input v-model="form.confirmPassword" placeholder="请输入确认密码" maxlength="32" />
                  </el-form-item>
                  <el-form-item label="所属角色" prop="userType">
                    <el-select v-model="form.userType" filterable allow-create default-first-option
                    :reserve-keyword="false" placeholder="请选择角色">
                      <el-option v-for="(item, index) in userTypeList " :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="角色权限" prop="roleId">
                    <el-select v-model="form.roleId" multiple filterable allow-create default-first-option
                    :reserve-keyword="false" placeholder="请选择权限">
                      <el-option v-for="(item, index) in roleIdList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="所属职位" prop="workPosition">
                     <el-input v-model="form.workPosition" placeholder="请输入所属职位" maxlength="30" />
                  </el-form-item>
                  <el-form-item label="所在部门" prop="deptName">
                     <el-input v-model="form.deptName" placeholder="请输入所在部门" maxlength="30" />
                  </el-form-item>
                  <el-form-item label="员工姓名" prop="nickname">
                     <el-input :disabled="typeOpen!=1" v-model="form.nickname" placeholder="请输入员工姓名" maxlength="20" />
                  </el-form-item>
                  <el-form-item label="邮箱地址" prop="email">
                     <el-input :disabled="typeOpen!=1" style="width:60%" v-model="form.email" placeholder="请输入邮箱地址" maxlength="30" />
                     <!-- <el-button v-if="typeOpen==1" :disabled="countdownEmail > 0" style="margin-left:20px" type="primary" @click="getCode('email')"> {{ countdownEmail > 0 ? countdownEmail + '秒' : '验证码' }}</el-button> -->
                  </el-form-item>
                  <el-form-item label="手机号" prop="mobile">
                     <el-input :disabled="typeOpen!=1" style="width:60%" v-model="form.mobile" placeholder="请输入手机号" maxlength="13" />
                     <el-button v-if="typeOpen==1" :disabled="countdownPhone > 0" style="margin-left:20px" type="primary" @click="getCode('phone')"> {{ countdownPhone > 0 ? countdownPhone + '秒' : '验证码' }}</el-button>
                  </el-form-item>
                  <el-form-item  v-if="typeOpen==1" label="验证码" prop="smsCode">
                     <el-input v-model="form.smsCode" placeholder="请输入手机号验证码" style="width:60%"  maxlength="20" />
                  </el-form-item>
      
                  <!-- <el-form-item v-if="typeOpen==1" label="验证码" prop="emailCode">
                     <el-input v-model="form.emailCode" placeholder="请输入邮箱验证码" maxlength="8" />
                  </el-form-item>          -->
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitForm(userRef)">确 定</el-button>
               <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import Table from '@/views/components/table/index.vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue'
import { getRolesPage, getRoleMenuList,getRolerolesList, deleteRole, updateRoleStatus, addUser,updateUser, getPhoneCode, getEmailCode,getRoleDetailById, } from '@/api/systemManage/accout/index'
import type { FormInstance, FormRules } from 'element-plus'
// 联级选择器 默认全部展开（官方不支持默认全部展开 需相应方法协作展开）
const userRef=ref()
const queryRef=ref(null)
const dialogUserRole=ref(false) //弹框
const  roleIdList=ref([])
const userTypeList=ref([
  { label: '管理员', value: 2 },
  { label: '普通用户', value: 3 }
  ]) 

const data = reactive({
  form: {},
  queryParams: {
    username:'',
    nickname:'',
    mobile:'',
    examineStartTime:'',
    examineEndTime:'',
    createStartTime:'',
    createEndTime:'',
    email:'',
    pageNum: 1,
    pageSize: 10,
  },
  rules: {
   username: [{ required: true, message: "账号不能为空", trigger: "blur" }, { min: 6, max: 20, message: "用户名称长度必须介于 6 和 20 之间", trigger: "blur" }],
   password: [{ required: true, message: "密码不能为空", trigger: "blur" }, { min: 8, max: 32, message: "密码长度必须介于 8 和 32 之间", trigger: "blur" }, { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: "blur" }],
   confirmPassword: [{ required: true, message: "确认密码不能为空", trigger: "blur" }, { min: 8, max: 32, message: "确认密码长度必须介于 8 和 32 之间", trigger: "blur" }, { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: "blur" }],
    roleId: [{ required: true, message: "请选择角色权限", trigger: "blur" }],
    userType: [{ required: true, message: "账号类型不能为空", trigger: "blur" }],
    nickname: [{ required: true, message: "员工姓名不能为空", trigger: "blur" }],
    mobile: [{ required: true, pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }],
    smsCode: [{required: true, message: "手机验证码不能为空", trigger: "blur" }],
    email: [{required: true,  type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }],
    // emailCode: [{ required: true, message: "邮箱验证码不能为空", trigger: "blur" }],
  }
});
const { queryParams, form, rules } = toRefs(data);

onMounted(() => {
  getPermission()
  getFilterData()

})

// 基础数据
const tableData = reactive({
  header: [
    { key: 'username', colWidth: '60', title: '登录账号', type: 'name', isCheck: true },
    { key: 'nickname', colWidth: '60', title: '员工姓名', type: 'name', isCheck: true },
    { key: 'roleNames', colWidth: '60', title: '角色', type: 'name', isCheck: true },
    { key: 'userType', colWidth: '60', title: '账号类型', type: 'name', isCheck: true },
    { key: 'mobile', colWidth: '60', title: '手机号', type: 'name', isCheck: true },
    { key: 'email', colWidth: '60', title: '邮箱地址', type: 'name', isCheck: true },
    { key: 'createTime', colWidth: '80', title: '注册日期', type: 'createTime', isCheck: true },
    { key: 'status', colWidth: '40', title: '状态', type: 'status', isCheck: true },

    {
      key: 'operate',
      colWidth: '60',
      title: '操作',
      type: 'operate',
      isCheck: true,
      buttons: [
        {
          icon: 'Edit',
          type: 0,  //企业用户 1  企业账号 0 
          status: "1",
          command: 'editPermissions',
          content: '',
        },
        {
          icon: 'Open',
          type: 0,  //企业用户 1  企业账号 0 
          status: "1",
          command: 'handleSwitch',
          content: '',
        },
        {
          icon: 'Delete',
          type: 0,  //企业用户 1  企业账号 0 
          command: 'deleteBox',
          content: '',
        }
      ]
    }
  ],
  data: [],
  config: {
    isSelection: false,
    isList: false,
    isPagination: true, // 是否分页
    total: 0, // 总条数
    loading: false,
    isRealName: false, // 是否已经实名认证
  }
})
//获取角色权限列表
const getPermission = () => {
  getRolerolesList({}).then(res => {
    roleIdList.value=res.data
  })
}
// const getPermission = () => {
//   getRoleMenuList().then(res => {
//     roleIdList.value=res.data
//     roleIdList.value=roleIdList.value.filter(c=>c?.roleId==15 || c?.roleId==16)
//   })
// }


// 重置搜索数据
const resetFrome = () => {
  queryRef.value.resetFields()
  queryParams.value.createStartTime=''
  queryParams.value.createEndTime=''
  queryParams.value.examineStartTime=''
  queryParams.value.examineEndTime=''
}
// 搜索数据
const getFilterData = () => {
  getRolesPage(JSON.stringify(queryParams.value)).then(res => {
    tableData.data = res.data.list.sort((a, b) => a.sort - b.sort)
    tableData.config.total = res.data.total
    console.log(res)
  })
}

// 获取手机/邮箱 验证码
const getCode = (type) => {
    if (type == 'phone' && form.value.mobile) {
         if(!form.value.mobile){
                ElMessage.warning("请输入手机号");
                return false
            }
            const data = {
                "mobile": form.value.mobile
            }
        getPhoneCode(data).then(res => {
            console.log(res)
            if (res.code == "00000") {
                ElMessage.success('发送成功')
                sendVerificationCode(type)
            }
        })
    } else if (type == 'email' && form.value.email) {
        getEmailCode(form.value.email).then(res => {
            console.log(res)
            if (res.code == "00000") {
                ElMessage.success('发送成功')
                sendVerificationCode(type)
            }
        })
    } else {
        ElMessage.warning('请检查手机号或邮箱是否填写正确')
    }
}

// 倒计时的秒数
const countdownPhone = ref(0);
const countdownEmail = ref(0);

// 发送验证码函数
const sendVerificationCode = (type) => {
  if(type == 'phone'){
     // 如果倒计时已经开始，则直接返回
   if (countdownPhone.value > 0) return;

    // 设置倒计时为60秒
    countdownPhone.value = 60;
    // 启动定时器，每秒减少一秒
    const timer = setInterval(() => {
      countdownPhone.value--;
        // 当倒计时结束时，清除定时器
        if (countdownPhone.value === 0) {
          clearInterval(timer);
        }
    }, 1000)
  }else if(type=='email'){
       // 如果倒计时已经开始，则直接返回
   if (countdownEmail.value > 0) return;
    // 设置倒计时为60秒
    countdownEmail.value = 60;
    // 启动定时器，每秒减少一秒
    const timer = setInterval(() => {
      countdownEmail.value--;
        // 当倒计时结束时，清除定时器
        if (countdownEmail.value === 0) {
          clearInterval(timer);
        }
    }, 1000)
  }
  
}
/** 提交按钮 */
const submitForm = (formEl: FormInstance | undefined) =>{
  // form.value.smsCode='DA_SHUAI_BI_888888'  //验证码写死上线去掉
  if (!formEl) return
  formEl.validate(valid => {
   if(form.value.password!=form.value.confirmPassword){
      ElMessage.warning("两次输入的密码不一致！");
      return false
   }
   let dataForm=JSON.parse(JSON.stringify(form.value))
   if(dataForm.roleId.length>0){
    dataForm.roleId=dataForm.roleId.join(',')
   }
    if (valid) {
      if (form.value.id != undefined) {
        dataForm.userId=dataForm.id
        updateUser(dataForm).then(response => {
          cancel();
          getFilterData()
        });
      } else {
        addUser(dataForm).then(response => {
          cancel();
          getFilterData()
      
        });
      }
    }
  });
};
//关闭弹框
const cancel = () => {
  typeOpen.value=1
  userRef.value.resetFields()// 重置数据
  dialogUserRole.value=false
}
const typeOpen=ref(1) //1新增 2编辑
// 新增弹窗
const addPermissionRoleDialog = (row) => {
  typeOpen.value=1
  dialogUserRole.value=true
}

// 编辑
const editPermissions = (row) => {
  typeOpen.value=2
  dialogUserRole.value=true
  getRoleDetail(row)
}
//详情查询
const getRoleDetail=(row)=>{
  getRoleDetailById(row).then(res => {
    form.value=res.data
    let roleId=res.data.roleId.split(",") || []
    let roleIdList=[]
    roleId.forEach((item)=>{
      roleIdList.push(parseInt(item))
    })
    form.value.roleId=roleIdList
  })
}



//删除操作
const deleteBox = (row) => {
  ElMessageBox.confirm(
    '确认删除该条账号信息吗？',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      deleteRole(row.id).then((res) => {
        console.log('dele', res)
        ElMessage.success('账号删除成功')
        getFilterData()
      })
    })
}
// 切换状态 updateRoleStatus
const handleSwitch = (row, statu) => {
  console.log(row, statu)
  let messTitle = ''
  if (statu == '1') {
    messTitle = '该账号即将启用？'
  } else if (statu == '0') {
    messTitle = '该账号即将停用？'
  }
  ElMessageBox.confirm(
    messTitle,
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      updateRoleStatus(row, statu).then(res => {
        console.log(res)
        getFilterData()
        ElMessage.success('状态修改成功')
      }).catch(error => {
        ElMessage.warning('状态修改失败')
      })
    })


}
// 翻页控制
const pageChange = (val) => {
  getRolesPage(JSON.stringify(val)).then(res => {
    tableData.data = res.data.list.sort((a, b) => a.sort - b.sort)
    tableData.config.total = res.data.total
    console.log(res)
  })
}

</script>

<style scoped>
 .box-container{
    padding: 20px;
}
.choose-item-2 {
  margin-left: 20px;
}
.choose-item-3 {
  display: block;
  margin-left: 20px;
}
</style>